import { readFile } from 'node:fs/promises';
import path from 'node:path';

function getPackageManager() {
  const userAgent = process.env.npm_config_user_agent;
  if (userAgent?.startsWith("bun")) {
    return "bun";
  } else if (userAgent?.startsWith("yarn")) {
    return "yarn";
  } else if (userAgent?.startsWith("pnpm")) {
    return "pnpm";
  } else {
    return "npm";
  }
}
function getPackageExecutor(external = true) {
  const packageManager = getPackageManager();
  if (packageManager === "yarn") {
    return external ? "yarn dlx" : "yarn";
  } else if (packageManager === "pnpm") {
    return external ? "pnpx" : "pnpm";
  } else if (packageManager === "bun") {
    return "bunx";
  } else {
    return "npx";
  }
}
async function hasDependency(name, dev = false) {
  try {
    const packageJsonPath = path.join(process.cwd(), "package.json");
    const packageJson = JSON.parse(await readFile(packageJsonPath, "utf-8"));
    if (dev) {
      return !!packageJson.devDependencies?.[name];
    }
    return !!packageJson.dependencies?.[name];
  } catch {
    return false;
  }
}
const IS_BUN_PM = getPackageManager() === "bun";
const IS_BUN_RUNTIME = process.versions.bun;

export { IS_BUN_PM, IS_BUN_RUNTIME, getPackageExecutor, getPackageManager, hasDependency };
